package com.gxuwz.medical.domain.payment;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import com.gxuwz.medical.database.DbUtil;
import com.gxuwz.medical.exception.PayperiodUnfoundException;
import com.gxuwz.medical.tools.DateUtil;

/**
 * 缴费时间设置模块
 * 
 * @author 演示
 * 
 */
public class Payperiod {
	/**
	 * 缴费执行年度
	 */
	private int runyear;
	/**
	 * 缴费金额
	 */
	private double amount;
	/**
	 * 起始时间 yyyy-MM-dd
	 */
	private String startime;
	/**
	 * 结束时间 yyyy-MM-dd
	 */
	private String endtime;
	/**
	 * 状态：1 启用，0 停用
	 */
	private String status;

	public Payperiod(int runyear) throws PayperiodUnfoundException {
		if (runyear == 0) {
			throw new IllegalArgumentException("the param runyear can not be 0");
		} else {
			this.runyear = runyear;
			try {
				load();
			} catch (SQLException e) {
				throw new PayperiodUnfoundException(runyear + "年度的缴费标准未设置！", e);
			}
		}
	}

	/**
	 * 校验缴费是否过期
	 * 
	 * @return
	 * @throws Exception
	 */
	public boolean available() throws Exception {

		try {
			// 判断缴费时间是否大于结束时间
			return DateUtil.isAfterNow(this.endtime);
		} catch (Exception e) {
			e.printStackTrace();
			throw e;
		}
	}

	/**
	 * 
	 * @throws SQLException
	 */
	private void load() throws SQLException {
		// 定义数据库连接实例变量
		Connection conn = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		try {
			conn = DbUtil.getConn();
			String sql = "select * from t_payperiod where runyear=?";
			pstmt = conn.prepareStatement(sql);
			int index = 1;
			// 依次设置动态参数对应的值
			pstmt.setInt(index, this.runyear);
			rs = pstmt.executeQuery();
			// 执行next()方法
			rs.next();
			this.runyear = rs.getInt("runyear");
			this.amount = rs.getDouble("amount");
			this.startime = rs.getString("startime");
			this.endtime = rs.getString("endtime");
			this.status = rs.getString("status");
		} catch (SQLException e) {
			e.printStackTrace();
			throw new SQLException("failed load ID=" + this.runyear
					+ " record from database!", e);
		}
	}

	public int getRunyear() {
		return runyear;
	}

	public void setRunyear(int runyear) {
		this.runyear = runyear;
	}

	public double getAmount() {
		return amount;
	}

	public void setAmount(double amount) {
		this.amount = amount;
	}

	public String getStartime() {
		return startime;
	}

	public void setStartime(String startime) {
		this.startime = startime;
	}

	public String getEndtime() {
		return endtime;
	}

	public void setEndtime(String endtime) {
		this.endtime = endtime;
	}

	public String getStatus() {
		return status;
	}

	public void setStatus(String status) {
		this.status = status;
	}

}
